package com.atguigu.gmall.common.config.thread;

import com.atguigu.gmall.common.config.thread.properties.ThreadProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Description
 * @Return
 * @Author https://weiranyi.github.io
 * @Date Created in 2022-12-05 17:58
 * @EnableConfigurationProperties 注解的作用是:让使用了 @ConfigurationProperties 注解的类生效,并且将该类注入到 IOC 容器中,交由 IOC 容器进行管理
 **/
@EnableConfigurationProperties({ThreadProperties.class})
@Configuration
public class ThreadPoolAutoConfiguration {
    @Autowired
    ThreadProperties threadProperties;

    // 自定义连接池
    @Bean
    public ThreadPoolExecutor coreExecutor() {
        return new ThreadPoolExecutor(
                threadProperties.getCorePoolSize(),
                threadProperties.getMaximumPoolSize(),
                threadProperties.getKeepAliveTime(),
                TimeUnit.MINUTES,
                new LinkedBlockingQueue<>(threadProperties.getWorkQueueSize()),
                new ThreadFactory() {
                    int i = 1;

                    @Override
                    public Thread newThread(Runnable r) {
                        Thread thread = new Thread(r);
                        thread.setName("核心线程[" + i++ + "]");
                        thread.setPriority(10);
                        return thread;
                    }
                },
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
    }
}
